package userManagement;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import db.DatabaseConnector;
import java.math.BigInteger;
import java.security.MessageDigest;

public class UserAdded extends HttpServlet {
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
	PrintWriter out = response.getWriter();
	DatabaseConnector DBConnect = new DatabaseConnector(DatabaseConnector.getDatabaseType());

	out.println("<html><head><title>User Addition -- Result</title>");
	out.println("<script type=\"text/javascript\" src=\"../userManager.js\"></script>");
	out.println("</head><body>");

	String[] in = {"*"};
	Object[] check = DBConnect.selectSQL("USERS",in,"username",request.getParameter("username")); // Retrieve connection information
	try{
            if (check[0].equals("null")){ }//triggers catch if does not exist
		out.println("<body onload=directToAdd(\"?"
			  + "username=" + request.getParameter("username")
			  + "&password=" + request.getParameter("password")
			  + "&email=" + request.getParameter("email")
			  + "&groups=" + request.getParameter("groups")
			  + "&loadCase=existent"
			  + "\")>Redirecting you to Add New User...</body></html>");
            }
        catch (NullPointerException npe) {
            String pwd = null;
            pwd = HashPassword(request.getParameter("password"));
            in = new String[]{ (request.getParameter("username")),pwd };
            String[] params = {"username","password"};
            DBConnect.insertSQL("USERS",params,in);

            in = new String[] {request.getParameter("username"),request.getParameter("email")};
            params[1] = "email";
            DBConnect.insertSQL("USER_INFO",params,in);

            boolean chat = false;

            //insert groups
            String reqGroups = request.getParameter("groups");
                if (!reqGroups.equals("")) {
                    String[] groups = reqGroups.split(";");
                    params[1] = "role";
                    for (int i=0;i<groups.length;i++){
                        if (groups[i].equals("chat")) chat = true;
                            in = new String[]{ request.getParameter("username"),groups[i] };
                            DBConnect.insertSQL("USER_ROLES",params,in);
                    }
                }

		if (chat){ //add to chatUsers group
                    String SQL = "INSERT INTO chatUsers (username,chatID,removed) Values (?,?,?)";
                    DBConnect.freeformSQL(SQL,new Object[]{request.getParameter("username"),0,0});
                }

		out.println("<h3>User '"+ request.getParameter("username") +"' successfully added!</h3>");
		out.println("<a href=\"ListUsers\">Return to User Listing</a></body></html>");
            }
            finally
            {
                DBConnect.CleanUp();
            }
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		doPost(request, response);
	}

    private String HashPassword(String p)
    {
        String hp = "";
        try
        {
            MessageDigest m=MessageDigest.getInstance("MD5");
            byte[] data = p.getBytes();
            m.update(data, 0, data.length);
            BigInteger i = new BigInteger(1,m.digest());
            hp = String.format("%1$032X", i);
            return hp;

        }
        catch (Exception e)
        {
            System.out.println(e.getClass()+ ", " + e.getMessage());
        }
        return hp;
    }
}